package com.qi.utils;

import com.qi.entity.Department;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Description 部门树
 * @Author dingchunlin
 * @Date 2024/3/16 14:04
 * @Version 1.0.0
 */
public class DepartmentTree {

    /**
     * 生成部门树学习
     * @param departmentList 部门列表
     * @param pid 父id
     * @return
     */
    public static List<Department> makeDepartmentTree(List<Department> departmentList,Long pid){
        //首先创建一个返回类
        List<Department> result = new ArrayList<Department>();
        //判断部门列表是否为空，为空则进行创建
        Optional.ofNullable(departmentList).orElse(new ArrayList<Department>())
                .stream().filter( item -> item != null && item.getPid().equals(pid))
                .forEach( item ->{
                    //创建部门对象
                    Department department = new Department();
                    //复制属性
                    BeanUtils.copyProperties(item, department);
                    //获取每一个item的下级部门，通过递归生成部门树
                    List<Department> children = makeDepartmentTree(departmentList, item.getId());
                    //设置子部门
                    department.setChildren(children);
                    //将部门添加到部门集合中
                    result.add(department);
                });
        return result;
    }

}
